<template>
  <div class="usertask">
    <el-collapse-item name="usertask">
      <template #title>
        <el-icon class="title-icon">
          <UserFilled />
        </el-icon>用户任务
      </template>
      <el-form label-width="auto" class="form" :data="usertaskInfo">
        <el-form-item label="人员类型：">
          <el-radio-group v-model="isOtherUser">
            <el-radio-button label="发起人" value="false" @click="setinitiator"></el-radio-button>
            <el-radio-button label="其他人" value="true" @click="setOther"></el-radio-button>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="指定人员：">
          <div style="display:flex; width: 100%;">
            <el-text style="width: 392px;">
              <el-tag type="primary">{{ usertaskInfo.assignee?.name }}</el-tag>
            </el-text>

            <el-button type="primary" @click="setAssignee" :disabled="!isOtherUser"><el-icon>
                <Search />
              </el-icon></el-button>
            <el-button type="danger" @click="usertaskInfo.assignee = ''"><el-icon>
                <CircleClose />
              </el-icon></el-button>
          </div>
        </el-form-item>
        <el-form-item label="候选人员：">
          <div style="display:flex; width: 100%;">
            <el-text style="width: 392px;">
              <el-tag v-for="(item) in usertaskInfo.candidateUsers" :key="item.id" type="primary">{{ item.name
                }}</el-tag>
            </el-text>

            <el-button type="primary" @click="setCandiUsers"><el-icon>
                <Search />
              </el-icon></el-button>
            <el-button type="danger" @click="usertaskInfo.candidateUsers = ''"><el-icon>
                <CircleClose />
              </el-icon></el-button>
          </div>
        </el-form-item>
        <el-form-item label="候选岗位：">
          <div style="display:flex; width: 100%;">
            <el-text style="width: 392px;">
              <el-tag type="primary" v-for="item in
                usertaskInfo.candidateGroups" :key="item.id">{{ item.name }}</el-tag>
            </el-text>
            <el-button type="primary" @click="groupDrawerVisible = true"><el-icon>
                <Search />
              </el-icon></el-button>
            <el-button type="danger" @click="usertaskInfo.candidateGroups = ''"><el-icon>
                <CircleClose />
              </el-icon></el-button>
          </div>
        </el-form-item>
        <el-form-item label="到期时间：">
          <el-row style="width: 100%;">
            <el-col :span="5">
              <el-text>{{ usertaskInfo.dueDate }}</el-text>
            </el-col>

            <el-col :span="9">
              <el-input-number v-model="dueData.time" placeholder="时间" :min="1">
              </el-input-number>
            </el-col>
            <el-col :span="5">
              <el-select placeholder="单位" class="dueDataSelect" v-model="dueData.unit">
                <el-option label="分钟" value="PT&M"></el-option>
                <el-option label="小时" value="PT&H"></el-option>
                <el-option label="日" value="P&D"></el-option>
                <el-option label="周" value="P&W"></el-option>
                <el-option label="月" value="P&M"></el-option>
              </el-select>

            </el-col>
            <!-- <el-col :span="3.5"></el-col> -->
            <el-col :span="5" style="display: flex; justify-content: flex-end;">
              <el-button type="danger" @click="usertaskInfo.dueDate = ''"><el-icon>
                  <CircleClose />
                </el-icon></el-button>
            </el-col>
          </el-row>
        </el-form-item>
        <el-form-item label="优先级：">
          <div style="display:flex; width: 100%; justify-content: space-between">
            <el-input v-model="usertaskInfo.priority" style="width: 360px"></el-input>
            <el-button type="danger" @click="usertaskInfo.priority = ''"><el-icon>
                <CircleClose />
              </el-icon></el-button>
          </div>
        </el-form-item>

      </el-form>
    </el-collapse-item>
    <!-- 选择员工 -->
    <el-drawer title="选择人员" v-model="drawerVisible" size="580">
      <el-row>
        <TreeSlideShow :list="adminStore.deptList" :span="8" @getNodeData="getDepNodeData"></TreeSlideShow>
        <el-col :span="14" :offset="0">
          <el-table ref="userSelectRef" :data="userlist" style="width: 100%" @select="handleUserSeclect">
            <el-table-column v-if="isAssignee" align="center">
              <template #default="scope">
                <el-radio :label="scope.$index" v-model="currentRow"
                  @change="getCurrentRow(scope.row)">&nbsp;</el-radio>
              </template>
            </el-table-column>
            <el-table-column v-if="!isAssignee" align="center" type="selection">
            </el-table-column>
            <el-table-column align="center" label="姓名" prop="name">
            </el-table-column>
            <el-table-column align="center" label="岗位" prop="job">
            </el-table-column>
          </el-table>
          <div style="display: flex; width:100%; ">
            <el-pagination size="small" layout="prev, pager, next" :total="pagination.total" style="margin-left: auto;"
              hide-on-single-page />
          </div>
        </el-col>
      </el-row>
      <template #footer>
        <div>
          <el-button @click="closeUserSelect">取消</el-button>
          <el-button type="primary" @click="drawerVisible = false">确认</el-button>
        </div>
      </template>
    </el-drawer>
    <!-- 岗位选择抽屉 -->
    <el-drawer title="岗位选择" v-model="groupDrawerVisible" size="580">
      <el-row>
        <TreeSlideShow :list="adminStore.deptList" :span="8" @getNodeData="getJobNodeData"></TreeSlideShow>
        <el-col :span="14" :offset="0">
          <el-table ref="groupSelectRef" :data="grouplist" style="width: 100%" @select="handleGroupsSeclect">
            <el-table-column align="center" type="selection">
            </el-table-column>
            <el-table-column align="center" label="岗位" prop="name">
            </el-table-column>
          </el-table>
          <div style="display: flex; width:100%; ">
            <el-pagination size="small" layout="prev, pager, next" :total="pagination.total" style="margin-left: auto;"
              hide-on-single-page />
          </div>
        </el-col>
      </el-row>
      <template #footer>
        <div style="flex: auto;">
          <el-button @click="closeGroupSelect">取消</el-button>
          <el-button type="primary" @click="groupDrawerVisible = false">确认</el-button>
        </div>
      </template>
    </el-drawer>
  </div>
</template>

<script setup>
import { ref, watch } from 'vue'
const element = defineModel("element",
  //  {
  //   default: {
  //     id: '',
  //     name: '',
  //     type: ''
  //   }
  // }
)
const props = defineProps({
  bpmnModeler: Object
})

const isOtherUser = ref()
const usertaskInfo = ref({
  assignee: '',
  candidateUsers: '',
  candidateGroups: '',
  dueDate: '',
  priority: '',
})
const dueData = ref({
  time: '',
  unit: ''
})
import { getUserListByIDs, getJobListByIDs } from '@/api/flowable/defination'
const userlistinit = ref([])
async function init() {
  console.log('init')
  usertaskInfo.value = {
    assignee: '',
    candidateUsers: '',
    candidateGroups: '',
    dueDate: '',
    priority: '',
  }
  let ids = []
  console.log('element', element.value.$attrs["flowable:assignee"] === '${initiator}')
  // TODO 修改发起人
  // if (element.value?.$attrs["flowable:assignee"] === '${initiator}') {
  if (element.value?.$attrs["flowable:assignee"] === '${initiator}') {
    usertaskInfo.value.assignee = { id: '${initiator}', name: '发起人' }
    // console.log(usertaskInfo.value.assignee)
    isOtherUser.value = false
  } else if (element.value.$attrs["flowable:assignee"]) {
    ids.push(element.value.$attrs["flowable:assignee"])
    isOtherUser.value = true
  }
  let users = ''
  if (element.value?.$attrs["flowable:candidateUsers"]) {
    console.log('type', typeof (element.value?.$attrs["flowable:candidateUsers"]))
    console.log((element.value?.$attrs["flowable:candidateUsers"]))
    users = element.value?.$attrs["flowable:candidateUsers"].split(',')
    for (let i = 0; i < users.length; i++) {
      ids.push(users[i])
    }
    console.log(ids)
  }
  if (ids.length > 0) {
    ids = Array.from(new Set(ids))
    console.log('ids', ids)
    await getUserListByIDs(ids).then(res => {
      userlistinit.value = res.data.data
      console.log(res.data.data)
    })
  }
  if (element.value?.$attrs["flowable:assignee"] !== '${initiator}' && element.value?.$attrs["flowable:assignee"]) {
    usertaskInfo.value.assignee = userlistinit.value.filter(item => {
      console.log('验证', item.id === Number.parseInt(element.value.$attrs["flowable:assignee"]))
      return item.id === Number.parseInt(element.value.$attrs["flowable:assignee"])
    })[0]
  }
  // else {
  //   usertaskInfo.value.assignee = ''
  // }
  if (element.value?.$attrs["flowable:candidateUsers"]) {
    usertaskInfo.value.candidateUsers = userlistinit.value.filter(item => users.includes(item.id.toString()))
  } else {
    usertaskInfo.value.candidateUsers = []
  }
  if (element.value?.candidateGroups) {
    console.log(element.value.candidateGroups)
    await getJobListByIDs(element.value.candidateGroups).then(res => {
      usertaskInfo.value.candidateGroups = res.data.data
    })
  } else {
    usertaskInfo.value.candidateGroups = []
  }
  if (element.value?.dueDate) {
    let dueDateOri = element.value.dueDate
    if (dueDateOri.startsWith('PT')) {
      dueData.value.time = dueDateOri.slice(2, -1)
      dueData.value.unit = ''.concat('PT&').concat(dueDateOri.slice(-1))
    } else if (dueDateOri.startsWith('P')) {
      dueData.value.time = dueDateOri.slice(1, -1)
      dueData.value.unit = ''.concat('P&').concat(dueDateOri.slice(-1))
    }
  } else {
    dueData.value.time = ''
    dueData.value.unit = ''
  }
  if (element.value?.priority) {
    usertaskInfo.value.priority = element.value.priority
  } else {
    usertaskInfo.value.priority = ''
  }
}

init()
watch(element, () => {
  console.log('element变化', element)
  init()
}, { deep: true }
)
// 设定发起人还是其他人
function setinitiator() {
  usertaskInfo.value.assignee = { id: '${initiator}', name: '发起人' }

  isOtherUser.value = false
}
function setOther() {
  usertaskInfo.value.assignee = ''
  isOtherUser.value = true
  usertaskInfo.value.assignee = ''
}
const isAssignee = ref(false)
function setAssignee() {
  isAssignee.value = true
  drawerVisible.value = true
}
function setCandiUsers() {
  isAssignee.value = false
  drawerVisible.value = true
}
// 拼接dueData
watch(dueData, (newVal) => {
  if (newVal.time && newVal.unit) {
    usertaskInfo.value.dueDate = newVal.unit.replace('&', newVal.time)
    console.log(usertaskInfo.value.dueDate)
    // usertaskInfo.value.dueDate = `${newVal.time}${newVal.unit}`
  }
}, { deep: true })
// 人员选择对话框
const drawerVisible = ref(false)
const userSelectRef = ref()
import TreeSlideShow from '@/components/tree/TreeSlideShow.vue';
import { useAdminStore } from '@/stores'
import { userGetListBySearch } from '@/api/setting'
const adminStore = useAdminStore()
const pagination = ref({
  page: 1,
  pageSize: 10,
  total: null,
})
const userlist = ref([])
async function getDepNodeData(nodeData) {
  console.log(nodeData.id)
  await userGetListBySearch({ username: "", name: "", status: "", deptId: nodeData.id, job: "", roleId: "", page: pagination.value.page, pageSize: pagination.value.pageSize })
    .then(res => {
      console.log(res.data.data.records)
      userlist.value = res.data.data.records
      pagination.value.total = res.data.data.total
    })
}
function closeUserSelect() {
  if (isAssignee.value) {
    usertaskInfo.value.assignee = []
  } else {
    usertaskInfo.value.candidateUsers = ''
  }
  drawerVisible.value = false
}
// table自定义单选框
const currentRow = ref('')
function getCurrentRow(row) {
  console.log(row)

  usertaskInfo.value.assignee = row
}
function handleUserSeclect() {
  // 直接对数据JSON化
  // usertaskInfo.value.candidateUsers = JSON.stringify(userSelectRef.value.getSelectionRows())
  // 更新属性时JSON化
  usertaskInfo.value.candidateUsers = userSelectRef.value.getSelectionRows()
}
// 用户选择确认

// 岗位选择
const grouplist = ref([])
const groupDrawerVisible = ref(false)
function getJobNodeData(row) {
  // console.log(row)
  grouplist.value = []
  row.joblist.forEach(item => {
    grouplist.value.push(item)
  })
  console.log(grouplist.value)
}
function handleGroupsSeclect(row) {

  usertaskInfo.value.candidateGroups = row
}
function closeGroupSelect() {
  if (usertaskInfo.value.candidateGroups) {
    usertaskInfo.value.candidateGroups = ''
  }
  groupDrawerVisible.value = false
}
// 数据update至modeler


watch(usertaskInfo, () => {
  console.log('updateBPMN')
  const editElement = props.bpmnModeler.get("elementRegistry").get(element.value.id)
  const modeling = props.bpmnModeler.get("modeling")
  if (usertaskInfo.value.assignee) {
    modeling.updateProperties(editElement, {
      'flowable:assignee': usertaskInfo.value.assignee.id
    })
  } else {
    delete editElement.businessObject.$attrs[`flowable:assignee`]
  }

  if (usertaskInfo.value.candidateUsers?.length > 0) {
    modeling.updateProperties(editElement, {
      'flowable:candidateUsers': usertaskInfo.value.candidateUsers.map(item => item.id).toString()
    })
  } else {
    delete editElement.businessObject.$attrs[`flowable:candidateUsers`]
  }
  if (usertaskInfo.value.candidateGroups?.length > 0) {
    modeling.updateProperties(editElement, {
      'flowable:candidateGroups': usertaskInfo.value.candidateGroups.map(item => item.id).toString()
    })
  } else {
    delete editElement.businessObject.candidateGroups
  }
  if (usertaskInfo.value.dueDate) {
    modeling.updateProperties(editElement, {
      'flowable:dueDate': usertaskInfo.value.dueDate
    })
  } else {
    delete editElement.businessObject.dueDate
  }
  if (usertaskInfo.value.priority) {
    modeling.updateProperties(editElement, {
      'flowable:priority': usertaskInfo.value.priority
    })
  } else {
    delete editElement.businessObject.priority
  }
}, { deep: true })
</script>

<style lang="less" scoped>
:deep(.el-collapse-item__header) {
  font-weight: 700;
  background-color: var(--el-color-primary-light-9);
  border-radius: 10px;

  .title-icon {
    margin: 0 10px;
  }
}

.form {
  padding: 15px;

  .el-tag {
    margin-right: 5px;
  }

  .dueDataSelect {
    width: 100px;
  }
}
</style>